import Toast from '@vant/weapp/toast/toast'
var pageNo = 1;
var pageSize = 10;
const app = getApp();
var picRoot = app.data.picRoot;
var url = app.data.platFormUrl;
var urlOp = app.data.url;
var util = require('../../utils/util.js');
var common = require('../../utils/common.js');
var QQMapWX = require('../../utils/qqmap-wx-jssdk.js');
import Dialog from '@vant/weapp/dialog/dialog';
var qqmapsdk;
var env = "";
var open = "";
var phone = "";

var date = util.formatDate(new Date().getTime());
var time = util.formatTime(new Date().getTime());
var map = new Map();

var startDate; //接龙日期 yyyy-MM-dd
var startTime; //计时开始时间 时间戳
var currentDate; //当前时间
var timer;     //计时器
var count = 0; //计时器频率 秒
var jielongStartTime;
var jielongEndTime;

var startPoint; //拖动接龙按钮

Page({
  /**
   * 页面的初始数据
   */
  data: {
    //jielongTimeZone: [{ "startTime": "11:00:00", "endTime": "11:20:00" }, { "startTime": "21:50:00", "endTime": "22:07:00"}], //当前餐饮商家自行设置的接龙时间段
    //jielongTimeZoneStr:"11:00:00～11:20:00、21:50:00～22:07:00",
    jielongDesChecked: false,
    isJielongAddressAllowed : false,
    jielongTimeZone: [],
    jielongTimeZoneStr: '',
    jielongDeliveryDistance: 0,
    jielongDeliveryDistanceStr: '',
    jielongId: '',
    jielongPayOrderId: '',
    isShareByJielong: 'N', //是否接龙分享页面入口进来
    jielongShow:false,       //接龙按钮显示标志
    showJielongPopup: false,
    jielongLongitude: '',
    jielongLatitude: '',
    jielongAddress: '',
    jielongPhone: '',
    jielongOnsureBtnShow: false,
    jielongOrderId: '',
    jielongCountingDown: 58 * 60 * 1000,
    jielongCountingDownShow1: false,
    jielongCountingDownShow2: false,
    mark: '',
    allowedDistance: 2,
    noticeBarShow1: true,
    specStatus: false,
    tabActive: 0,
    active: 0,
    currentTab: 0,
    mainActiveIndex: 0,
    activeId: null,
    imageURL: "",
    currentDate: new Date().getTime(),
    hiddenmodalput: true, //可以通过hidden是否掩藏弹出框的属性，来指定那个弹出框
    showDate: false,
    showTime: false,
    title: '',
    timeValue: '',
    dateValue: '',
    address: '广州市天河区万胜围1号',
    latitude: '',
    longitude: '',
    merchantName: '',
    phone: '',
    cart: [],
    selectCart: [],
    hideModal: true, //模态框的状态  true-隐藏  false-显示
    animationData: {},
    desk: [],
    bookDeskMsg: '',
    merchantId: '',
    displayDate: date,
    displayTime: time,
    minHour: 10,
    maxHour: 20,
    currentDate: new Date().getTime(),
    minDate: new Date().getTime(),
    itemTypeList: [],
    classifyType: 0,
    totalPrice: 0,
    totalNum: 0,
    changeDetail: 0,
    queryType: 0,
    show: false,
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      } else if (type === 'month') {
        return `${value}月`;
      }
      return `${value}日`;
    },
    imgData: [],
    imgNewsData: [],
    preShow: false,
    submitStatus: false,
    peopleShow: false,
    peopleNum: '',
    btnClick: '',
    orderType: '',
    deskNo: '',
    takeOutTime: '',
    send: '',
    deskTitle: '',
    sendTitle: '',
    specShow: false,
    result: [],
    specList: [],
    itemName: '',
    itemPrice: '',
    tempItemPrice: '',
    tempRadioItemPrice: '',
    tempPrice: '',
    radioSelectPrice: 0,
    checkBoxSelectPrice: 0,
    specSelectIdList: [],
    item: [],
    sendPrice: 0,
    selectRadio: '',
    onLoadData: '',
    inHallPreMenu: 0,
    hallBtnClick: 0,
    isShowBtn: 0,
    popTitle: '请输入预定信息',
    rightHeight: 0,

    //接龙按钮
    buttonTop: 0,
    buttonLeft: 0,
    windowHeight: '',
    windowWidth: ''
    
  },
 
  specStatusChange: function (event) {
    let _that = this;
    console.log(event);
    _that.setData({
      specStatus: event.detail
    });
  },
  envPreviewImg: function (e) {
    let imgUrl = e.currentTarget.dataset.image;
    let _that = this //图片预览
    let envPic = _that.data.imgData;
    wx.previewImage({
      current: imgUrl, // 当前显示图片的http链接
      urls: envPic // 需要预览的图片http链接列表
    })
  },

  previewImg: function (e) {
    let imgUrl = e.currentTarget.dataset.image;
    let _that = this //图片预览
    wx.previewImage({
      current: imgUrl, // 当前显示图片的http链接
      urls: [imgUrl] // 需要预览的图片http链接列表
    })
  },
  /**确认选择规格项 */
  choose: function (option) {
    let _that = this;
    let item = _that.data.item;
    let resultArr = _that.data.result;
    let specSelectIdList = [];
    let specName = '';
    for (var i = 0; i < resultArr.length; i++) {
      let result = resultArr[i];
      let arr = result.split("-");
      specSelectIdList.push(arr[0]);
      specName += arr[2];
      if (i != resultArr.length - 1) {
        specName += ","
      }
    }
    let selectRadio = _that.data.selectRadio;
    let arr = [];
    for (let i in selectRadio) {
      let radio = selectRadio[i];
      let radioArr = radio.split("-");
      if (radioArr.length >= 3) {
        let name = radioArr[2];
        arr.push(name);
        specSelectIdList.push(name);
      }
    }
    if (arr.length > 0 && specName != '') {
      specName += ",";
    }
    for (var i = 0; i < arr.length; i++) {
      specName += arr[i];
      if (i != arr.length - 1) {
        specName += ","
      }
    }
    // 数字正序排列
    specSelectIdList.sort(common.compareAsc);
    let specIdList = '';
    for (var i = 0; i < specSelectIdList.length; i++) {
      let specId = specSelectIdList[i];
      specIdList += specId;
      if (i != specSelectIdList.length - 1) {
        specIdList += ","
      }
    }
    let selectCart = _that.data.selectCart;
    let tempJson = {};
    tempJson.id = item.id;
    tempJson.itemType = _that.data.active;
    // 当前按钮只能选择一个
    tempJson.num = 1;
    tempJson.order = item.order;
    let itemPrice = _that.data.itemPrice;
    tempJson.price = itemPrice
    tempJson.title = item.title;
    if(specName == '' || specName == undefined){
      // 没有点餐
      console.log(169);
      tempJson.tempId = specIdList ? specIdList : -1;
      specIdList = -1;
    } else {
      console.log(172);
      tempJson.tempId = specIdList ? specIdList : specName;
    }
    
    tempJson.specDesc = specName;
    // console.log(tempJson);
    const tempSelectCart = [];
    let map = new Map();
    for (var i = 0; i < selectCart.length; i++) {
      if (selectCart[i].tempId) {
        console.log(177);
        tempSelectCart.push(selectCart[i]);
        selectCart[i].oNum = i;
        map.set(selectCart[i].tempId, selectCart[i]);
      } 
    }
    if (tempSelectCart.length != 0) {
     
      let mapItem = map.get(specIdList);
      if (mapItem) {
        mapItem.num++;
        selectCart[mapItem.oNum] = mapItem;
      } else {
        selectCart.push(tempJson);
      }
    } else {
      selectCart.push(tempJson);
    }
    let totalPrice = _that.data.totalPrice * 100;
    totalPrice += itemPrice * 100
    let tNum = _that.data.totalNum + 1;
    for (var i = 0; i < selectCart.length; i++) {
        selectCart[i].price = selectCart[i].price * 1;
    }
    _that.setData({
      specSelectIdList: specSelectIdList,
      selectCart: selectCart,
      totalNum: tNum,
      totalPrice: totalPrice / 100,
      specShow: false,
      submitStatus: false,
    })
  },
  /**单选框 */
  onRadioChange(event) {
    let _that = this;
    let tempRadioItemPrice = _that.data.tempRadioItemPrice * 100;
    let checkBoxSelectPrice = _that.data.checkBoxSelectPrice * 100;
    let tempPrice = _that.data.tempPrice * 100;

    //林启升 fix 2020-08-09 start
    let selectRadio = null
    try {
      selectRadio = JSON.parse(JSON.stringify(_that.data.selectRadio));
    } catch (e) {
      selectRadio = {}
    }
    selectRadio = selectRadio || {}
    const id = event.target.id
    selectRadio[id] = event.detail;
    for (let key in selectRadio) {
      let result = selectRadio[key];
      let arr = result.split("-");
      console.log(arr);
      let price = arr[1];
      tempRadioItemPrice += price * 100
    }
    _that.setData({
      selectRadio: selectRadio,
      tempRadioItemPrice: 0,
      radioSelectPrice: tempRadioItemPrice / 100,
      itemPrice: (tempRadioItemPrice + tempPrice + checkBoxSelectPrice) / 100
    });
    //林启升 fix 2020-08-09 end

  },
  /**复选框 */
  onCheckBoxChange(event) {
    let _that = this;
    console.log(event.detail);
    let resultArr = event.detail;
    let tempItemPrice = _that.data.tempItemPrice * 100;
    let radioSelectPrice = _that.data.radioSelectPrice * 100;
    let tempPrice = _that.data.tempPrice * 100;
    for (var i = 0; i < resultArr.length; i++) {
      let result = resultArr[i];
      let arr = result.split("-");
      let price = arr[1];
      tempItemPrice += price * 100;
    }
    this.setData({
      result: event.detail,
      tempItemPrice: 0,
      checkBoxSelectPrice: tempItemPrice / 100,
      itemPrice: (tempItemPrice + tempPrice + radioSelectPrice) / 100
    });
  },
  /**打开规格弹框 */
  openSpecPop: function (option) {
    let _that = this;
    let item = option.currentTarget.dataset.item;
    let order = option.currentTarget.dataset.order;
    item.order = order;
    // 加载
    _that.setData({
      specList: item.specList,
      specShow: true,
      submitStatus: true,
      itemName: item.title,
      itemPrice: item.payType == 1 ? item.discountPrice : item.price,
      tempItemPrice: 0,
      tempRadioItemPrice: 0,
      radioSelectPrice: 0,
      checkBoxSelectPrice: 0,
      tempPrice: item.payType == 1 ? item.discountPrice : item.price,
      item: item,
      result: [],
      selectRadio: {}
    })
  },
  /**关闭规格弹框 */
  closeSpecPo: function () {
    let _that = this;
    _that.setData({
      specShow: false,
      submitStatus: false
    })
  },
  deskNoChange: function (event) {
    let _that = this;
    _that.setData({
      deskNo: event.detail
    })
  },
  orderTypeChange: function (event) {
    let _that = this;
    _that.setData({
      orderType: event.detail
    })
  },
  sendBtnClickChange: function (option) {
    let _that = this;
    let send = option.currentTarget.dataset.send;
    let title = option.currentTarget.dataset.title;
    _that.setData({
      send: send,
      sendTitle: title
    })
  },
  btnClickChange: function (option) {
    let _that = this;
    let btnClick = option.currentTarget.dataset.btn;
    let title = option.currentTarget.dataset.title;
    _that.setData({
      btnClick: btnClick,
      deskTitle: title
    })
  },
  hallBtnClickChange: function (option) {
    let _that = this;
    let hallBtnClick = option.currentTarget.dataset.btn;
    let temp = 0;
    let isShowBtn = 0;
    if (hallBtnClick == 0) {
      temp = 0;
      isShowBtn = 0;
      _that.setData({
        totalNum: 0,
        totalPrice: 0,
      })
    } else {
      temp = 1;
      isShowBtn = 1;
      _that.loadMenu(_that.data.merchantId, _that.data.onLoadData);
    }
    _that.setData({
      hallBtnClick: hallBtnClick,
      inHallPreMenu: temp,
      isShowBtn: isShowBtn
    })
  },
  peopleChange: function (event) {
    this.setData({
      peopleNum: event.detail
    });
  },
  onPickerConfirm: function (event) {
    console.log(event);
  },
  onPeopleChange(event) {
    const {
      picker,
      value,
      index
    } = event.detail;
    Toast(`当前值：${value}, 当前索引：${index}`);
  },
  showPeoplePopup() {
    this.setData({
      peopleShow: true
    });
  },

  closePeoplePopup() {
    this.setData({
      peopleShow: false
    });
  },
  showOrderCartPopup() {
    let _that = this;
    // 如果是预定餐桌，则设置弹框确认按钮文案及调用方法
    /*let orderType = _that.data.ordertype;
    let isShowBtn = _that.data.isShowBtn;
    if (orderType == 'SUBSCRIBE_IN_HALL' && isShowBtn == 1) {
      _that.setData({
        isShowBtn: 0
      })
    }*/
    let tempShow = _that.data.show;
    if (tempShow) {
      _that.setData({
        show: false
      });
    } else {
      _that.setData({
        show: true
      });
    }
  },

  onClose() {
    let _that = this;
    _that.setData({
      show: false
    });
  },
  onCloseJielongPopup(){
    let _that = this;
    _that.setData({
      showJielongPopup: false
    });
  },
  jielongCancel(){
    let _that = this;
    _that.setData({
      showJielongPopup: false
    });
  },
  jielongOnsure() {
    let _that = this;
    _that.setData({
      showJielongPopup: false
    });
  },
  switchNav: function (e) {
    var page = this;
    var id = e.target.id;
    if (this.data.currentTab == id) {
      return false;
    } else {
      page.setData({
        currentTab: id
      });
    }
    page.setData({
      active: id
    });

  },
  touchmove: function (event) {
    return false;
  },
  onClickNav({
    detail = {}
  }) {
    this.setData({
      mainActiveIndex: detail.index || 0
    });
  },

  onClickItem({
    detail = {}
  }) {
    const activeId = this.data.activeId === detail.id ? null : detail.id;

    this.setData({
      activeId
    });
  },
  onConfirm(e) {
    this.setData({
      showDate: false
    });
    this.setData({
      currentDate: e.detail,
      displayDate: util.formatDate(e.detail)
    });
  },
  onCancel() {
    this.setData({
      showDate: false
    });
  },
  onConfirmTime(e) {
    this.setData({
      showTime: false
    });
    this.setData({
      //currentDate: e.detail,
      displayTime: e.detail
    });
  },
  onCancelTime() {
    this.setData({
      showTime: false
    });
  },
  onInput(event) {
    //获取操作改变的值
    //this.setData({
    //currentDate: event.detail
    //});
  },
  timePickerBindchange: function (e) {
    var _this = this;
    var tempTimeArr = _this.data.timeArr;
    this.setData({
      timeValue: tempTimeArr[e.detail.value]
    })
  },
  datePickerBindchange: function (e) {
    var _this = this;
    var tempDateArr = _this.data.dateArr;
    this.setData({
      dateValue: tempDateArr[e.detail.value]
    })
  },
  deleteStepper: function (e) {
    var _that = this;
    var id = e.currentTarget.dataset.id;
    var price = e.currentTarget.dataset.price;
    var title = e.currentTarget.dataset.title;
    var itemType = e.currentTarget.dataset.type;
    var order = e.currentTarget.dataset.order;
    var num = _that.data.changeDetail;
    var limitNum = e.currentTarget.dataset.limitnum;
    // key为id ， value为json
    var itemJson = {};
    itemJson.id = id;
    itemJson.price = price;
    itemJson.title = title;
    itemJson.num = num;
    itemJson.limitNum = limitNum;
    itemJson.itemType = itemType;
    itemJson.order = order;
    map.set(id, itemJson);
    let tempSelectCart = _that.data.selectCart;
    var cartArr = new Array();
    for (let i = 0; i < tempSelectCart.length; i++) {
      let temp = tempSelectCart[i];
      if (temp.tempId) {
        cartArr.push(tempSelectCart[i]);
      }
    }
    let tempPrice = _that.data.totalPrice * 100;
    // 同时处理cart;
    let carts = _that.data.cart;
    // console.log(carts);
    map.forEach(function (item, index, arr) {
      if (itemType == item.itemType && order == item.order) {
        let p = item.price * 100;
        tempPrice -= p;
      }
      cartArr.push(item);
      carts[item.itemType][item.order].num = item.num;
    });
    // 计算num总数
    let totalNum = 0;
    for (var i = 0; i < cartArr.length; i++) {
      totalNum += cartArr[i].num;
    }
    _that.setData({
      totalPrice: tempPrice / 100,
      cart: carts,
      selectCart: cartArr,
      totalNum: totalNum
    })
  },
  changeStepper: function (e) {
    let _that = this;
    _that.setData({
      changeDetail: e.detail
    })
  },
  addStepper: function (e) {
    var _that = this;
    var id = e.currentTarget.dataset.id;
    var price = e.currentTarget.dataset.price;
    var title = e.currentTarget.dataset.title;
    var itemType = e.currentTarget.dataset.type;
    var order = e.currentTarget.dataset.order;
    var limitNum = e.currentTarget.dataset.limitnum;
    var num = _that.data.changeDetail;
    // key为id ， value为json
    var itemJson = {};
    itemJson.id = id;
    itemJson.price = price;
    itemJson.title = title;
    itemJson.num = num;
    itemJson.limitNum = limitNum;
    itemJson.itemType = itemType;
    itemJson.order = order;
    map.set(id, itemJson);
    let tempSelectCart = _that.data.selectCart;
    console.info("----------*****************");
    console.info(map);
    console.info(tempSelectCart);
    var cartArr = new Array();
    for (let i = 0; i < tempSelectCart.length; i++) {
      let temp = tempSelectCart[i];
      if (temp.tempId) {
        cartArr.push(tempSelectCart[i]);
      }
    }
    let tempPrice = _that.data.totalPrice * 100;
    // 同时处理cart;
    let carts = _that.data.cart;
    console.info(carts);
    map.forEach(function (item, index, arr) {
      if (itemType == item.itemType && order == item.order) {
        let p = item.price * 100;
        tempPrice += p;
      }
      cartArr.push(item);
      carts[item.itemType][item.order].num = item.num;
    });
    // 计算num总数
    let totalNum = 0;
    for (var i = 0; i < cartArr.length; i++) {
      totalNum += cartArr[i].num;
    }
    // console.log("总金额: " + tempPrice);
    console.info(tempPrice / 100);
    console.info(carts);
    console.info(cartArr);
    console.info(totalNum);
    _that.setData({
      totalPrice: tempPrice / 100,
      cart: carts,
      selectCart: cartArr,
      totalNum: totalNum
    })
  },
  add: function (e) {
    // console.log(e);
    let _this = this;
    let carts = _this.data.cart;
    console.log(carts);
    // 获取当前选中的菜单分类
    var itemType = e.currentTarget.dataset.type;
    var order = e.currentTarget.dataset.order;
    let tempPrice = _this.data.totalPrice * 100;
    // console.log(selectCart);
    let selectCart = _this.data.selectCart;
    console.log(selectCart);
    for (var i = 0; i < selectCart.length; i++) {
      let temp = selectCart[i];
      if (!temp.tempId) {
        let item = carts[selectCart[i].itemType][selectCart[i].order];
        console.log(item);
        // 赋值
        if (itemType == selectCart[i].itemType && order == selectCart[i].order &&
          selectCart[i].num < 99) {
          console.log(0);
          item.num = ++selectCart[i].num;
          let p = selectCart[i].price * 100;
          tempPrice += p;
        }
      } else {
        console.log(1);
        let dataTempId = e.currentTarget.dataset.tempid;
        if (dataTempId == selectCart[i].tempId) {
          selectCart[i].num++;
          let p = selectCart[i].price * 100;
          tempPrice += p;
        }
      }
    }
    console.log(selectCart);
    // 计算num总数
    let totalNum = 0;
    for (var i = 0; i < selectCart.length; i++) {
      totalNum += selectCart[i].num;
    }
    _this.setData({
      totalPrice: tempPrice / 100,
      cart: carts,
      selectCart: selectCart,
      totalNum: totalNum
    })
  },
  delete: function (e) {
    // console.log(e);
    let _this = this;
    let carts = _this.data.cart;
    // 获取当前选中的菜单分类
    var itemType = e.currentTarget.dataset.type;
    var order = e.currentTarget.dataset.order;
    let selectCart = _this.data.selectCart;
    // console.log(selectCart);
    let tempPrice = _this.data.totalPrice * 100;
    for (var i = 0; i < selectCart.length; i++) {
      let temp = selectCart[i];
      if (!temp.tempId) {
        let item = carts[selectCart[i].itemType][selectCart[i].order];
        // 赋值
        if (itemType == selectCart[i].itemType && order == selectCart[i].order &&
          selectCart[i].num > 0) {
          item.num = --selectCart[i].num;
          tempPrice -= selectCart[i].price * 100;
        }
      } else {
        let dataTempId = e.currentTarget.dataset.tempid;
        if (dataTempId == selectCart[i].tempId) {
          selectCart[i].num--;
          tempPrice -= selectCart[i].price * 100;
        }
      }

    }
    // 计算num总数
    let totalNum = 0;
    for (var i = 0; i < selectCart.length; i++) {
      totalNum += selectCart[i].num;
    }
    _this.setData({
      totalPrice: tempPrice / 100,
      cart: carts,
      selectCart: selectCart,
      totalNum: totalNum
    })
  },
  deleteAllCart: function () {
    let _this = this;
    this.setData({
      selectCart: []
    })
  },
  toEnv: function () {
    //console.log(env);
    //console.log(open);
    wx.navigateTo({
      url: '../../pages/env/index?env=' + env,
    })
  },
  toTable: function () {
    wx.navigateTo({
      url: '../../pages/table/index',
    })
  },
  toNews: function () {
    wx.navigateTo({
      url: '../../pages/news/index?open=' + open,
    })
  },
  /**
   * 打开弹框
   */
  showPrePop: function () {
    let _that = this;
    let sendPrice = _that.data.sendPrice;
    let totalPrice = _that.data.totalPrice;
    let orderType = _that.data.orderType;
    if (orderType == 'TAKE_OUT') {
      if (totalPrice < sendPrice) {
        wx.showToast({
          title: "该店铺起送金额为" + sendPrice + "元!",
          icon: "none",
          duration: 2000
        })
        return;
      }
    } else if (orderType == 'SUBSCRIBE_IN_HALL') {
      _that.setData({
        isShowBtn: 0
      })
    }
    _that.setData({
      preShow: true,
      submitStatus: true,
      popTitle: '再次确认预约信息'
    })
  },
  showPayPop: function(){
    let _that = this;
    // 携带参数跳转页面
    /*wx.navigateTo({
      url: '../../pages/order-detail/index?queryType=' + queryType + "&merchantId=" + that.data.merchantId + "&tempData=" + jsonData,
    })*/
  },
  closePrePop: function () {
    let _that = this;
    _that.setData({
      preShow: false,
      submitStatus: false
    })
  },
  inHallClosePrePop: function () {
    let _that = this;
    _that.setData({
      preShow: false,
      submitStatus: false
    })
  },
  /**
   * 去预约
   */
  pay: function (option) {
    var that = this;
    var selectCart = this.data.selectCart;
    var item = []
    for (var i = 0; i < selectCart.length; i++) {
      item[i] = selectCart[i];
    }
    console.info("买单咯----------");
    console.info(item);
    //let orderType = that.data.orderType;
    //let specStatus = that.data.specStatus;
    //if(specStatus){
      // 商家配送且选择修改为自提
      //orderType = 'PICK_UP';
    //}

    if (item.length == 0) {
      wx.showToast({
        title: "请先点餐!",
        icon: "none",
        duration: 2000
      })
      return;
    }

    
    /*let inHallPreMenu = that.data.inHallPreMenu;
    if (orderType == 'SUBSCRIBE_IN_HALL' && inHallPreMenu == 1) {
      if (item.length == 0) {
        wx.showToast({
          title: "请先点餐!",
          icon: "none",
          duration: 2000
        })
        return;
      }
    } else if (orderType == 'SUBSCRIBE_IN_HALL' && inHallPreMenu == 0) {
      // 不需要点餐, 清空购物车，直接生成订单页
      console.log("清空购物车");
      item = [];
      that.setData({
        totalPrice: 0
      })

    } else {
      if (item.length == 0) {
        wx.showToast({
          title: "请先点餐!",
          icon: "none",
          duration: 2000
        })
        return;
      }
    }*/


    var jsonItem = JSON.stringify(item);

    // 获取时间
    /*var date = that.data.displayDate;
    var time = that.data.displayTime;
    var btnClick;
    var peopleNum;

    if (orderType == 'SUBSCRIBE_IN_HALL') {
      if (!that.data.deskTitle) {
        wx.showToast({
          title: "请选择桌型!",
          icon: "none",
          duration: 2000
        })
        return;
      }
      if (!that.data.peopleNum) {
        wx.showToast({
          title: "请选择就餐人数!",
          icon: "none",
          duration: 2000
        })
        return;
      }
      // 获取桌型
      btnClick = that.data.deskTitle;
      // 获取就餐人数
      peopleNum = that.data.peopleNum;
      // 获取时间
    } else if (orderType == 'IN_HALL') {
      if (!that.data.deskNo) {
        wx.showToast({
          title: "请输入台号!",
          icon: "none",
          duration: 2000
        })
        return;
      }
      btnClick = "台号: " + that.data.deskNo;
    } else if (orderType == 'TAKE_OUT') {
      if (!that.data.sendTitle) {
        wx.showToast({
          title: "请选择时间!",
          icon: "none",
          duration: 2000
        })
        return;
      }
      btnClick = "配送时间为:" + that.data.sendTitle;
    } else {
      btnClick = "自提时间为: " + date + " " + time
    }*/

    var merchantId = that.data.merchantId;
    var createUserName = app.globalData.openId
    var queryType = that.data.queryType;
    var totalPrice = that.data.totalPrice;
    let tempData = {
      itemApi: jsonItem,
      merchantId: merchantId,
      timeVal: date + " " + time,
      //deskVo: btnClick,
      token: createUserName,
      totalPrice: totalPrice,
      //peopleNum: peopleNum,
      //orderType: orderType,
      //inHallPreMenu: inHallPreMenu
    }
    let jsonData = JSON.stringify(tempData);
    console.info(jsonData);
    
    // 携带参数跳转页面
    console.info("是否接龙=" + that.data.isShareByJielong);
    console.info("接龙id=" + that.data.jielongId);
    wx.navigateTo({
      url: '../../pages/order-detail/index?queryType=' + queryType + "&merchantId=" + that.data.merchantId + "&tempData=" + jsonData + "&isShareByJielong=" + that.data.isShareByJielong + '&jielongId=' + that.data.jielongId + "&jielongPhone=" + that.data.jielongPhone + "&jielongAddress=" + that.data.jielongAddress + '&jielongPayOrderId=' + that.data.jielongPayOrderId
    })

  },
  
  // 加载菜单
  loadMenu: function (merchantId, obj) {
    console.info("商家id==============" + merchantId);
    let that = this;
    // 查询菜品分类
    wx.request({
      url: urlOp + '/ItemApi/queryItemListByMerchantId',
      data: {
        merchantId: merchantId
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        if (res.data.code == 200) {

          that.setData({
            title: obj.name,
            itemTypeList: res.data.data,
          })
          wx.setNavigationBarTitle({
            title: that.data.title
          })
          // 加载默认选中的菜单
          wx.request({
            url: urlOp + '/ItemApi/queryItemByMerchantIdAndItemTypeId',
            data: {
              pageNo: pageNo,
              pageSize: pageSize,
              merchantId: merchantId
            },
            method: 'POST',
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            success: function (res) {
              console.log(res);
              if (res.data.code == 200) {
                that.setData({
                  cart: res.data.data
                })
              } else {
                wx.showToast({
                  title: res.data.msg,
                  icon: "fail",
                  duration: 2000
                })
              }

            },
            fail: function (res) {
              console.info(res);
              console.info('submit fail');
            },
            complete: function (res) {
              console.info('submit complete');
            }
          })
        } else {
          wx.showToast({
            title: '当前店铺无菜单',
            icon: "none",
            duration: 2000
          })
        }

      },
      fail: function (res) {
        console.info(res);
        console.info('submit fail1');
      },
      complete: function (res) {
        console.info('submit complete1');
      }
    })
  },
  onCountingFinish1: function(){
    this.setData({
      jielongCountingDown: new Date(this.jielongEndTime.replace(/-/g, "/")).getTime() - new Date(this.jielongStartTime.replace(/-/g, "/")).getTime(),
      jielongCountingDownShow1: false,
      jielongCountingDownShow2: true
    })
  },
  onCountingFinish2: function(){
    this.setData({
      jielongCountingDownShow2 : false,
      submitStatus : true
    })
  },
  getSysCurrentTimeAndCounting: function(option){
    var that = this;
    wx.request({
      url: url + '/CommonApi/client/noAuth/getCurrentSysTime',
      data: {},
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        //var time = res.data.data;
        //var year = time.substring(0, 11);
        //that.startTime = new Date(time.replace(/-/g, "/")).getTime();
        that.currentDate = res.data.data
        that.jielongStartTime = option.startTime;
        that.jielongEndTime = option.endTime;
        console.info("当前时间为 ===============" + that.currentDate);
        console.info(option.id);
        console.info(option.startTime);
        console.info(option.endTime);
        if (new Date(res.data.data.replace(/-/g, "/")).getTime() < new Date(option.startTime.replace(/-/g, "/")).getTime()){
          //时间还没到
           that.setData({
             jielongCountingDown: new Date(option.startTime.replace(/-/g, "/")).getTime() - new Date(res.data.data.replace(/-/g, "/")).getTime(),
             jielongCountingDownShow1 : true
           })
        } else if (new Date(res.data.data.replace(/-/g, "/")).getTime() >= new Date(option.startTime.replace(/-/g, "/")).getTime() && new Date(res.data.data.replace(/-/g, "/")).getTime() <= new Date(option.endTime.replace(/-/g, "/")).getTime()){
          //在接龙时间内
          that.setData({
            jielongCountingDown: new Date(option.endTime.replace(/-/g, "/")).getTime() - new Date(res.data.data.replace(/-/g, "/")).getTime(),
            jielongCountingDownShow2: true
          })
        } else {
          //在接龙时间后
          that.setData({
            submitStatus : true
          })
          wx.showToast({
            title: '该接龙点餐已结束',
            icon: "loading",
            duration: 3000,
            success: function () {
              setTimeout(function () {
                wx.switchTab({
                  url: '/pages/index/index'
                });
              }, 3000)
            }
          })
        }
        //计时
        //that.timer = setInterval(function () {
          //假设that.startTime获取到的时服务器时间的时间戳
          //count++;   //计时
          //console.info(that.startTime += 1000);
        //}, 1000)//每隔1s计时一次  如果你想更精确点，可以把时间间隔调为更小比如500

        //判断当前时间是否在商家设置的接龙时间区段内
        /*var flag = false;
        for (var i = 0; i < that.data.jielongTimeZone.length; i++) {
          that.data.jielongTimeZone[i].startTime = year + that.data.jielongTimeZone[i].startTime
          that.data.jielongTimeZone[i].endTime = year + that.data.jielongTimeZone[i].endTime
          if (that.startTime >= new Date(that.data.jielongTimeZone[i].startTime.replace(/-/g, "/")).getTime() && that.startTime <= new Date(that.data.jielongTimeZone[i].endTime.replace(/-/g, "/")).getTime()){
            flag = true;
            break;
          }
        }*/

          //判断有没超时,在点击点餐处也要做判断
          /*if (!flag){
            wx.showToast({
              title: '该接龙点餐已失效',
              icon: "loading",
              duration: 3000,
              success: function () {
                setTimeout(function () {
                  wx.switchTab({
                    url: '/pages/index/index'
                  });
                }, 3000)
              }
            })
          }*/
  
      },
      fail: function (res) {
        console.info('submit fail');
      },
      complete: function (res) {
        console.info('submit complete');
      }
    })
  },
  
  
  //以下是按钮拖动事件
  buttonStart: function (e) {
    startPoint = e.touches[0]//获取拖动开始点
  },
  buttonMove: function (e) {
    var endPoint = e.touches[e.touches.length - 1]//获取拖动结束点
    //计算在X轴上拖动的距离和在Y轴上拖动的距离
    var translateX = endPoint.clientX - startPoint.clientX
    var translateY = endPoint.clientY - startPoint.clientY
    startPoint = endPoint//重置开始位置
    var buttonTop = this.data.buttonTop + translateY
    var buttonLeft = this.data.buttonLeft + translateX
    //判断是移动否超出屏幕
    if (buttonLeft + 50 >= this.data.windowWidth) {
      buttonLeft = this.data.windowWidth - 50;
    }
    if (buttonLeft <= 0) {
      buttonLeft = 0;
    }
    if (buttonTop <= 0) {
      buttonTop = 0
    }
    if (buttonTop + 50 >= this.data.windowHeight) {
      buttonTop = this.data.windowHeight - 50;
    }
    this.setData({
      buttonTop: buttonTop,
      buttonLeft: buttonLeft
    })
  },
  buttonEnd: function (e) {
  },
  
  onLoad: function (option) {
    console.log(option);
    var that = this;
    var obj = JSON.parse(option.data);
    that.setData({
      onLoadData: obj,
      isShareByJielong: option.isShareByJielong ? option.isShareByJielong : 'N',
      jielongId: option.jielongId ? option.jielongId : '',
      jielongPhone: option.jielongPhone ? option.jielongPhone : '',
      jielongAddress: option.jielongAddress ? option.jielongAddress : ''
    })
    
      //获取手机可视高度，设置商家菜单高度，塞满
      wx.getSystemInfo({
        success: function (res) {
          // 获取可使用窗口宽度
          let clientHeight = res.windowHeight;
          // 获取可使用窗口高度
          let clientWidth = res.windowWidth;
          // 算出比例
          let ratio = 750 / clientWidth;
          //手机型号
          let mobileModel = res.model;
          // 算出高度(单位rpx)
          let height = clientHeight * ratio;
          console.info("---------------------------------" + height + "--------------------------")
          //高度减去顶部和底部
          height = height-44*2-50.5*2;
          if (mobileModel.indexOf("iPhone XR") != -1
            || mobileModel.indexOf("iPhone XS") != -1
            || mobileModel.indexOf("iPhone 11") != -1){
            height = height - 50;
            if (option.orderType == 'TAKE_OUT'){
               //商家配送
               console.info("----------------------再减少20-------------");
              height = height - 70;
            }
          }
          console.info("---------------------------------" + height + "--------------------------")
          console.info("-------------------" + mobileModel + "---------------");
          //设置高度
          that.setData({
            rightHeight: height
          })
          //接龙按钮相关参数设置
          that.setData({
            //corner_data: 3, //定义角标数字
            windowHeight: res.windowHeight,
            windowWidth: res.windowWidth,
            buttonTop: res.windowHeight * 0.80,//这里定义按钮的初始位置
            buttonLeft: res.windowWidth * 0.80,//这里定义按钮的初始位置
          })
        }
      });
    //}

    //let sendPrice = option.sendPrice;
    env = obj.env;
    var array = []
    if (env) {
      array = env.split(",");
      for (var i = 0; i < array.length; i++) {
        array[i] = picRoot + array[i];
      }
    }
    open = obj.open;
    var array2 = [];
    if (open) {
      array2 = open.split(",");
      for (var i = 0; i < array2.length; i++) {
        array2[i] = picRoot + array2[i];
      }
    }

    phone = obj.phone;
    
    map = new Map();
    /*qqmapsdk = new QQMapWX({
      //申请的腾讯地图位置服务密钥
      key: 'GSEBZ-FAFWX-PFD46-TEB2O-O2RE2-A5BGL'
    });*/

    that.setData({
      address: obj.addr,
      latitude: obj.lat,
      longitude: obj.lot,
      merchantName: obj.name,
      imgData: array,
      imgNewsData: array2,
      phone: phone,
      orderType: option.orderType,
      //sendPrice: sendPrice,
      merchantId: obj.id
    })
    var merchantId = that.data.merchantId = obj.id
    //加载菜单(顺便把该商家是否参与接龙相关信息查出来)
    that.loadMenu(merchantId, obj);  
    //加载接龙相关信息(时间区段,配送范围)
      wx.request({
        url: url + '/JielongTimeZoneApi/client/noAuth/listTimeZoneByMerchantId',
        data: {
          id: merchantId,
          jielongId: option.jielongId
        },
        method: 'POST',
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          if (res.data.code == 200) {
            if (res.data.data.length > 0){
                console.info("有时间");
              if (res.data.data[0].jielongCreateSuccess == "N") {
                wx.showToast({
                  title: '该接龙点餐发生异常失效,请重新发起',
                  icon: "loading",
                  duration: 3000,
                  success: function () {
                    setTimeout(function () {
                      wx.switchTab({
                        url: '/pages/index/index'
                      });
                    }, 3000)
                  }
                })
              }
                //显示店铺接龙时间提醒
                //jielongTimeZoneStr:"11:00:00～11:20:00、21:50:00～22:07:00",
                var str = '';
                for(var i = 0; i < res.data.data.length; i++){
                  str += res.data.data[i].startTime + '～' + res.data.data[i].endTime
                  if (i < res.data.data.length - 1){
                    str += '、';
                  }
                }
                that.setData({
                  jielongTimeZone: res.data.data,
                  jielongTimeZoneStr: str,
                  jielongDeliveryDistance: res.data.data[0].deliveryDistance,
                  jielongDeliveryDistanceStr: '温馨提示: 商家配送范围在' + res.data.data[0].deliveryDistance + 'km内' 
                })
              //获取服务器系统当前时间(用于接龙点餐)
              if (option.isShareByJielong != 'Y') {
                //餐饮商家列表点击进入 && 餐饮商家参与了接龙点餐活动
                that.setData({
                  jielongShow: true,
                  //noticeBarShow1: true,
                  rightHeight: that.data.rightHeight - 80
                })
              } else if (option.isShareByJielong == 'Y') {
                //餐饮商家参与了接龙点餐活动 && 从接龙分享页面进来
                that.getSysCurrentTimeAndCounting(option);
                that.setData({
                  noticeBarShow1: false,
                  jielongShow: false,
                  isShareByJielong: 'Y',
                  rightHeight: that.data.rightHeight - 70,
                  //生成子订单32位id,传给腾讯
                  jielongPayOrderId: util.wxuuid()
                })

              }
            } else {
              that.setData({
                noticeBarShow1: false
              
              })
            }
            
            
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: "fail",
              duration: 2000
            })
          }
        },
        fail: function (res) {
          console.info(res);
          console.info('submit fail');
        },
        complete: function (res) {
          console.info('submit complete');
        }
      })
    

    
    
    //let orderType = that.data.orderType;
    //console.log(orderType);
    // 订单类型为预约餐桌的, 查询桌型
    /*if (orderType == 'SUBSCRIBE_IN_HALL') {
      wx.request({
        url: url + '/ItemApi/queryBookingTypeById',
        data: {
          merchantId: merchantId
        },
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
          console.log(res);
          if (res.data.code == 200) {
            if (res.data.data.length > 0) {
              that.setData({
                desk: res.data.data
              })
            }
          } else {
            wx.showToast({
              title: '加载餐桌失败',
              icon: "loading",
              duration: 2000
            })
          }

        },
        fail: function (res) {
          console.info('submit fail');
        },
        complete: function (res) {
          console.info('submit complete');
        }
      })
    } else if (orderType == 'TAKE_OUT') {
      wx.request({
        url: url + '/EatSystemApi/queryTakeOutTimeAll',
        data: {
          merchantId: merchantId
        },
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
          console.log(res);
          if (res.data.code == 200) {
            if (res.data.data.length > 0) {
              that.setData({
                sendList: res.data.data
              })
            }
          } else {
            wx.showToast({
              title: '加载失败',
              icon: "loading",
              duration: 2000
            })
          }

        },
        fail: function (res) {
          console.info('submit fail');
        },
        complete: function (res) {
          console.info('submit complete');
        }
      })

      // 加载起送金额
      wx.request({
        url: url + '/ItemSendPriseApi/querySendPriseByMerchantId',
        data: {
          id: merchantId
        },
        method: 'POST',
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          if (res.data.code == 200) {
            let item = res.data.data;
            that.setData({
              sendPrice: item.price
            })
          }
        },
        fail: function (res) {
          console.info('submit fail');
        },
        complete: function (res) {
          console.info('submit complete');
        }
      })


    } else if (orderType == 'IN_HALL'){
      // 即时就餐, 新增二维码扫码点餐初始化餐台
      let deskNo = option.deskNo;
      if(deskNo){
        let _that = this;
        _that.setData({
          deskNo: deskNo
        })
      }
    }*/

  },
  /**
   * 上拉触底加载更多数据
   */
  onReachBottom: function () {
    // var pageNoReach = 1
    // pageNoReach = pageNoReach + 1;
    // var that = this;
    // var merchantId = that.data.merchantId;
    // wx.request({
    //   url: 'http://' + url + '/ItemApi/queryItemByMerchantIdAndItemTypeId',
    //   data: {
    //     pageNo: pageNoReach,
    //     pageSize: pageSize,
    //     merchantId: merchantId,
    //     classifyType: this.data.classifyType
    //   },
    //   method: 'POST',
    //   header: {
    //     'content-type': 'application/x-www-form-urlencoded'
    //   },
    //   success: function(res) {
    //     console.info(res.data);
    //     if (res.data.code == 200) {
    //       if (res.data.data.pageList.length > 0) {
    //         that.setData({
    //           cart: that.data.cart.concat(res.data.data.pageList)
    //         })
    //       }
    //     } else {
    //       wx.showToast({
    //         title: res.data.msg,
    //         icon: "loading",
    //         duration: 2000
    //       })
    //     }

    //   },
    //   fail: function(res) {
    //     console.info('submit fail');
    //   },
    //   complete: function(res) {
    //     console.info('submit complete');
    //   }

    // })
  },

  /**
   * 监听用户下拉动作(下拉刷新)
   */
  onPullDownRefresh: function () {
    //显示顶部刷新图标
    wx.showNavigationBarLoading();
    console.info("刷新拉");
  },
  modalinput: function () {
    this.setData({
      hiddenmodalput: !this.data.hiddenmodalput
    })
  },
  //取消按钮 
  cancel: function () {
    //清除预定数
    //let _this = this;
    //let desks = _this.data.desk;
    //for (var index in desks) {
    //desks[index].bookCount = 0;
    //}
    this.setData({
      //desk: desks,
      hiddenmodalput: true
    });
  },
  //确认 
  confirm: function (e) {
    //组装餐桌数据
    let _this = this;
    let desks = _this.data.desk;
    console.info(desks);
    let bookMsg = '';
    for (var index in desks) {
      if (desks[index].bookCount > 0) {
        bookMsg += desks[index].bookDesc;
        bookMsg += desks[index].bookCount;
        bookMsg += desks[index].unit;
        bookMsg += ' ';
      }
    }
    if (bookMsg.length > 18) {
      bookMsg = bookMsg.substring(0, 18) + "...";
    }
    this.setData({
      bookDeskMsg: bookMsg,
      hiddenmodalput: true
    })
  },
  plusDesk: function (e) {
    let _this = this;
    let desks = _this.data.desk;
    let num = e.currentTarget.dataset.index; //下标
    let de = desks[num];
    let max = de.leftCount; //最大值
    if (de.bookCount != max) {
      de.bookCount = ++de.bookCount;
      this.setData({
        desk: desks,
      });
    }
  },
  minusDesk: function (e) {
    let _this = this;
    let desks = _this.data.desk;
    let num = e.currentTarget.dataset.index; //下标
    let de = desks[num];
    if (de.bookCount != 0) {
      de.bookCount = --de.bookCount;
      this.setData({
        desk: desks,
      });
    }
  },
  makeCall: function () {
    console.log("打电话");
    wx.makePhoneCall({
      phoneNumber: phone,
      success: function () {
        console.log("成功拨打电话")
      },
      fail: function () {
        console.log("拨打电话失败！")
      }
    })

  },
  location: function () {
    var that = this;
    var name = this.data.merchantName;
    var addr = this.data.address;
    //使用后台维护的腾讯服务经纬度(火星坐标系)
    wx.openLocation({
      longitude: Number(this.data.longitude),
      latitude: Number(this.data.latitude),
      name: name,
      address: addr
    })
  },
  popupDate: function () {
    this.setData({
      showDate: true
    });
  },
  popupTime: function () {
    this.setData({
      showTime: true
    });
  },
  onShow: function () {
    wx.hideHomeButton({
      success: (res) => {},
    })
  },
  onJielongDesChange: function (event){
    var that = this;
    that.setData({
      jielongDesChecked: event.detail
    })
  },
  updateJielongDesChecked: function(uuid,flag){
     console.info("该用户不再显示接龙说明信息");
    wx.request({
      url: urlOp + '/ItemApi/updateJielongDesChecked?uuid=' + uuid + '&flag=' + flag,
      data: {},
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.setStorage({
          key: "isShowJielongDes",
          data: 'N'
        })
      },
      fail: function (res) {
        console.info(res);
        console.info('submit fail1');
      },
      complete: function (res) {
        console.info('submit complete1');
      }
    })
  },
  jielongClick: function(){

    var that = this;
    wx.getStorage({
      key: 'isShowJielongDes',
      success: function (res) {
        console.info(res.data);
        if('Y' == res.data){
          //接龙说明展示
          Dialog.alert({
            title: '餐饮接龙活动说明,请仔细阅读',
            message: '弹窗内容',
          }).then(() => {
            // on close
            if (that.data.jielongDesChecked) {
              //不再显示
              wx.getStorage({
                key: 'openId',
                success: function (res) {
                  console.info(res.data);
                  that.updateJielongDesChecked(res.data, 'N');
                },
              })
            }

          });
        }
      },
    })
    
    that.setData({ showJielongPopup: true });
    //获取订单id(后台生成雪花id)
      wx.request({
        //url: url + '/CommonApi/client/noAuth/getSnowNextId', platform版本
        url: urlOp + '/ItemApi/getNewOrderId',
        data: {},
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
          //var id = res.data.data.id; platform版本
          console.info(res);
          var id = res.data.data.orderId; 
          var time = res.data.data.currentTime;
          var year = time.substring(0, 11);
          that.startTime = new Date(time.replace(/-/g, "/")).getTime();
          that.startDate = year;
          //计时(每秒,有一点点偏差)
          that.timer = setInterval(function () {
            //假设that.startTime获取到的时服务器时间的时间戳
            count++;   //计时
            //console.info(that.startTime += 1000);
          }, 1000)//每隔1s计时一次  如果你想更精确点，可以把时间间隔调为更小比如500
          that.setData({
            jielongOrderId : id
          })
        },
        fail: function (res) {
          console.info(res);
          console.info('submit fail1');
        },
        complete: function (res) {
          console.info('submit complete1');
        }
      })
    
    
  },
  mapView: function () {
    var th = this;
    wx.chooseLocation({
      success: function (res) {
        var s1 = res.longitude + "";
        var s2 = res.latitude + "";
        var str1 = s1.substring(0, s1.indexOf(".") + 7);
        var str2 = s2.substring(0, s2.indexOf(".") + 7);
        th.setData({
          jielongLongitude: str1,
          jielongLatitude: str2,
          jielongAddress: res.address
        })
        var dist = th.distance(23.073746, 113.349473, str2, str1);
        console.info("本次选择地点经纬度 : ");
        console.info(str2);
        console.info(str1);
        console.info("距离店铺 : ");
        console.info(dist);
        //判断所选地址，在不在商家可送范围，显示确认按钮
        if (dist < th.data.allowedDistance){
          th.setData({
            isJielongAddressAllowed: true,
            jielongDeliveryDistanceStr: '温馨提示: 所选地址商家可以送达'
          })
          if (th.data.jielongPhone && th.data.isJielongAddressAllowed){
            th.setData({
              jielongOnsureBtnShow: true
            })
          }
        } else {
          console.info("超了超了");
          th.setData({
            isJielongAddressAllowed: false,
            jielongOnsureBtnShow: false,
            jielongDeliveryDistanceStr: '温馨提示: 所选地址超出商家可配送范围,请重新选择'
          })
          //Toast('所选地址超出商家可配送范围');
          //Toast.fail({ message: '所选地址超出商家可配送范围', duration: 0});
        }
        
      },
      fail: function () {
        // fail
      },
      complete: function () {
        // complete
      }
    })
  },
  distance: function (la1, lo1, la2, lo2) {
    var La1 = la1 * Math.PI / 180.0;
    var La2 = la2 * Math.PI / 180.0;
    var La3 = La1 - La2;
    var Lb3 = lo1 * Math.PI / 180.0 - lo2 * Math.PI / 180.0;
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(La3 / 2), 2) + Math.cos(La1) * Math.cos(La2) * Math.pow(Math.sin(Lb3 / 2), 2)));
    s = s * 6378.137;//地球半径
    s = Math.round(s * 10000) / 10000;
    // return s
    console.log("计算结果",s)
    return s;
  },
  onPhoneChange: function (event){
    let _that = this;
    //赋值
    _that.setData({
      jielongPhone: event.detail
    });
    //电话号码清空（小于11位或者大于11位），隐藏确定按钮
    if (!event.detail || event.detail.length < 11 || event.detail.length > 11){
      _that.setData({
        jielongOnsureBtnShow: false
      })
    }
    //电话号码11位 并且 接龙地址符合要求
    if (event.detail.length == 11 && _that.data.isJielongAddressAllowed){
      _that.setData({
        jielongOnsureBtnShow: true
      })
    }
  },
  onAddressChange: function (event){
    let _that = this;
    //赋值
    _that.setData({
      jielongAddress: event.detail
    });
    if (!event.detail) {
      console.info("地址清空了");
      _that.setData({
        jielongOnsureBtnShow: false,
        isJielongAddressAllowed: false,
        jielongLatitude: '',
        jielongLongitude: '',
        jielongDeliveryDistanceStr: '温馨提示: 商家配送范围在' + _that.data.jielongDeliveryDistance + 'km内'
      })
    }
  },
  onMarkChange: function (event) {
    let _that = this;
    _that.setData({
      mark: event.detail
    });
  },
  createJielongOrder: function (id,start,end,phone,address,merchantId,lat,lng,mark){
    wx.request({
      //url: url + '/preOrderApi/client/noAuth/createJielongOrder', platform版本
      url: urlOp + '/OrderApi/insertJielongOrder',
      data: {
        //id: id,  platForm版本
        orderId: id,
        startTime: start,
        endTime: end,
        phone: phone,
        address: address,
        merchantId: merchantId,
        lat: lat,
        lng: lng,
        mark:mark
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        console.log(res);
      },
      fail: function (res) {
        console.info(res);
        console.info('submit fail');
      },
      complete: function (res) {
        console.info('submit complete');
      }
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (ops) {
    let _that = this;
    let data = JSON.stringify(_that.data.onLoadData);
    let queryType = _that.data.queryType;
    let orderType = _that.data.orderType;
    let sendPrice = _that.data.sendPrice;
    let merchantName = _that.data.merchantName;
    //点击接龙
    if (ops.from === 'button'){
    //创建订单数据,根据当前时间绑定接龙时间区段(如果在某时间区间，则绑定该时间区间。 否则绑定下一接近时间区间)
      //判断当前时间是否在商家设置的接龙时间区段内
      var k = count;
      var timeZoneStart;
      var timeZoneEnd;
      for (var i = 0; i < _that.data.jielongTimeZone.length; i++) {
        //时间区段集合是排序好的,判断当前时间是否在时间区段之间内，首先先判断是否在该时间区段之前
        if (_that.startTime + k * 1000 <= new Date((_that.startDate + _that.data.jielongTimeZone[i].startTime).replace(/-/g, "/")).getTime()){
          //比如当前时间2021-04-17 15:00:00  时间区间 2021-04-17 15:10:00 - 2021-04-17 15:30:00
          timeZoneStart = _that.startDate + _that.data.jielongTimeZone[i].startTime;
          timeZoneEnd = _that.startDate + _that.data.jielongTimeZone[i].endTime; 
          break;
        }
        if (_that.startTime + k * 1000 >= new Date((_that.startDate + _that.data.jielongTimeZone[i].startTime).replace(/-/g, "/")).getTime() && _that.startTime + k * 1000 <= new Date((_that.startDate + _that.data.jielongTimeZone[i].endTime).replace(/-/g, "/")).getTime()) {
          //在某时间区间内,订单绑定该时间区间
          timeZoneStart = _that.startDate + _that.data.jielongTimeZone[i].startTime;
          timeZoneEnd = _that.startDate + _that.data.jielongTimeZone[i].endTime;
          break;
        }
      }
      
      if (!timeZoneStart) {
        //表示当前时间已经超过了该商家当天的所有时间区段,自动跳到明天第一时间区段
        var oneDayTimestamp = 24 * 60 * 60 * 1000;
        var tommorowStart = oneDayTimestamp + new Date((_that.startDate + _that.data.jielongTimeZone[0].startTime).replace(/-/g, "/")).getTime();
        var tommorowEnd = oneDayTimestamp + new Date((_that.startDate + _that.data.jielongTimeZone[0].endTime).replace(/-/g, "/")).getTime();
        console.info(_that.data.jielongTimeZone[0]);
        timeZoneStart = util.formatDateFull(tommorowStart);
        timeZoneEnd = util.formatDateFull(tommorowEnd);
      }
      console.info("订单id: =========" + _that.data.jielongOrderId);
      console.info("开始时间: =========" + timeZoneStart);
      console.info("结束时间: =========" + timeZoneEnd);
      //创建接龙订单
      _that.createJielongOrder(_that.data.jielongOrderId, timeZoneStart, timeZoneEnd, _that.data.jielongPhone, _that.data.jielongAddress, _that.data.merchantId, _that.data.jielongLatitude, _that.data.jielongLongitude, _that.data.mark);
      console.info(_that.data.jielongPhone);
      console.info(_that.data.jielongAddress);
      return {
        path: 'pages/detail/index?data=' + data + "&isShareByJielong=Y" + '&jielongId=' + _that.data.jielongOrderId + "&startTime=" + timeZoneStart + "&endTime=" + timeZoneEnd + "&jielongPhone=" + _that.data.jielongPhone + "&jielongAddress=" + _that.data.jielongAddress,
        title: merchantName
      }
    } else {
      //点击小程序右上角分享
      return {
        path: 'pages/detail/index?data=' + data + "&queryType=" + queryType + "&orderType=" + orderType + "&sendPrice=" + sendPrice,
        title: merchantName
      }
    }
    

    /*return {
      title: '接龙点餐开始啦～',
      path: '/pages/detail/index',
      imageUrl: 'http://static.e-mallchina.com/pic/product/brand/detail/hgds.jpg' //自定义图片路径，显示图片长宽比是 5:4。
    }*/
  }
})